<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="利润分配" name="payment">
          <el-form :inline="true" :model="listQuery">
            <el-form-item label="">
              <el-input
                size="small"
                v-model="listQuery.name"
                placeholder="支付单号/销售单号"
                clearable
                @keyup.enter.native="handleFilter"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="">
              <el-date-picker
                size="small"
                v-model="listQuery.search_date"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-search"
                @click.native="handleFilter"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                >新增{{ this.title }}</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            :data="paymentList"
            border
            size="small"
            v-loading="listLoading"
            fit
            highlight-current-row
          >
            <el-table-column type="expand" align="center">
              <template slot-scope="scope">
                <el-table
                  :data="scope.row.details"
                  border
                  v-if="scope.row.details.length > 0"
                  size="mini"
                >
                  <el-table-column
                    align="center"
                    label="姓名"
                    prop="lawyer_name"
                  />
                  <el-table-column
                    align="center"
                    label="职位"
                    prop="post_name"
                  />
                  <el-table-column
                    align="center"
                    label="比例(%)"
                    prop="ratio"
                  />
                  <el-table-column
                    align="center"
                    label="金额(元)"
                    prop="money"
                  />
                </el-table>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
              align="center"
              width="80px;"
            ></el-table-column>
            <el-table-column
              v-for="item in tableColumns"
              :key="item.key"
              align="center"
              :label="item.title"
              :prop="item.key"
              :formatter="dataFormatter"
            >
            </el-table-column>
            <el-table-column align="center" label="操作" width="180px">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleEdit(scope)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handleDelete(scope)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.page_size"
            @pagination="getPaymentList"
          />
        </el-tab-pane>

        <el-tab-pane label="利润分配明细" name="detail">
          <el-form :inline="true" :model="listCondition">
            <el-form-item label="">
              <el-select
                v-model="listCondition.name"
                placeholder="律师"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in employees"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-date-picker
                size="small"
                v-model="listCondition.search_date"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-search"
                @click.native="handleDetailFilter"
                >查询</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            :data="payDetailList"
            border
            size="small"
            v-loading="listLoading_detail"
            fit
            highlight-current-row
            show-summary
            :summary-method="getDetailSummaries"
          >
            <el-table-column
              type="index"
              label="#"
              align="center"
              width="80px;"
            ></el-table-column>
            <el-table-column
              v-for="item in tableDetailColumns"
              :key="item.key"
              align="center"
              :label="item.title"
              :prop="item.key"
              :formatter="dataFormatter"
            >
            </el-table-column>
            <el-table-column align="center" label="操作" width="120px">
              <template slot-scope="scope">
                <el-button
                  type="success"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleEdit(scope)"
                  >详情</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total_detail > 0"
            :total="total_detail"
            :page.sync="listCondition.page"
            :limit.sync="listCondition.page_size"
            @pagination="getPayDetailList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="60%">
      <el-form
        :model="paymentForm"
        :rules="paymentFormRules"
        ref="paymentFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 20px"
      >
        <!-- <el-form-item label="单号" prop="order_no" v-if="dialogType === 'edit'">
          <el-input
            type="text"
            v-model="paymentForm.order_no"
            placeholder="单号"
            maxlength="24"
            disabled
          />
        </el-form-item> -->
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="分配时间" prop="order_time">
              <el-date-picker
                v-model="paymentForm.order_time"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择开单时间"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售单" prop="sale_order">
              <el-select
                v-model="paymentForm.sale_order"
                placeholder="选择销售单"
                clearable
                @change="selectChange"
                :disabled="dialogType === 'edit'"
              >
                <el-option
                  v-for="item in sales"
                  :key="item.id"
                  :label="item.order_no"
                  :value="item.id"
                >
                  <span style="float: left"
                    >{{ item.order_no }}[{{ item.customer_name }}]</span
                  >
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.case_name
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customer_name">
              <el-input
                v-model="paymentForm.customer_name"
                placeholder="客户名称"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input
                v-model="paymentForm.desc"
                placeholder="备注"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-table :data="paymentForm.details" border size="small">
          <el-table-column label="律师">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.lawyer"
                placeholder="选择律师"
                clearable
              >
                <el-option
                  v-for="item in employees"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <!-- <el-input v-model="scope.row.lawyer" placeholder="律师"></el-input> -->
            </template>
          </el-table-column>
          <el-table-column label="职位">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.post"
                placeholder="请选择职位"
                clearable
              >
                <el-option
                  v-for="p in positions"
                  :key="p.value"
                  :label="p.label"
                  :value="p.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="比例">
            <template slot-scope="scope">
              <el-input v-model="scope.row.ratio" placeholder="比例">
                <template slot="append">%</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="金额">
            <template slot-scope="scope">
              <el-input v-model="scope.row.money" placeholder="金额">
                <template slot="append">元</template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="HandleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getParentsPath } from "@/utils/index";
import { getCurrentDate } from "@/utils/datetime";
import {
  getPayments,
  addPayment,
  updatePayment,
  delPayment,
  getPaymentDetails,
  getPaymentDetailByID,
} from "@/api/payment";
import { getSaleList } from "@/api/sale";
import { getEmployeeList } from "@/api/employee";
import { get_account_titles } from "@/api/account";
import { getBanks } from "@/api/bank";
import { positions } from "@/utils/const";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  order_no: "",
  order_time: getCurrentDate(),
  sale_order: null,
  customer_name: "",
  desc: "",
  user: null,
  details: [
    {
      id: null,
      payment: null,
      lawyer: null,
      post: null,
      ratio: 0,
      acc_title: null,
      account_type: null,
      money: 0,
      desc: "",
    },
  ],
};

export default {
  name: "Payment",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value <= 0) {
          callback(new Error("必须大于零"));
        } else {
          callback();
        }
      }
    };

    return {
      paymentForm: Object.assign({}, defaultForm),
      paymentFormRules: {
        sale_order: [
          { required: true, message: "请选择销售单", trigger: "blur" },
        ],
        order_time: [
          { required: true, message: "请输入开单时间", trigger: "blur" },
        ],
        acc_title: [
          { required: true, message: "请选择会计科目", trigger: "blur" },
        ],
        account_type: [
          { required: true, message: "请选择付款账户", trigger: "blur" },
        ],
        total_money: [{ validator: checkMoney, trigger: "blur" }],
      },

      title: "利润分配",
      activeName: "payment",
      accountList: [],
      employees: [],
      sales: [],
      banks: [],
      selectedKeys: [],
      positions,
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      dialogVisible: false,
      dialogType: "new",
      paymentList: [],
      payDetailList: [],
      total: 0,
      total_detail: 0,
      listLoading: true,
      listLoading_detail: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined,
        search_date: "",
      },
      listCondition: {
        page: 1,
        page_size: 20,
        name: undefined,
        search_date: "",
      },

      tableColumns: [
        {
          key: "sale_order_name",
          title: "销售单",
        },
        {
          key: "customer_name",
          title: "客户姓名",
        },
        {
          key: "order_time",
          title: "时间",
        },
        {
          key: "desc",
          title: "备注",
        },
      ],

      tableDetailColumns: [
        {
          key: "order_no",
          title: "支付单号",
        },
        {
          key: "order_time",
          title: "时间",
        },
        {
          key: "lawyer_name",
          title: "律师姓名",
        },
        {
          key: "post_name",
          title: "职位",
        },
        {
          key: "ratio",
          title: "利润比例(%)",
        },
        {
          key: "money",
          title: "金额(元)",
        },
        {
          key: "desc",
          title: "备注",
        },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getPaymentList();
    this.getAccounts();
    this.getEmployeeList();
    this.getSales();
    this.getBankList();
    this.getPayDetailList();
  },
  methods: {
    // 支付单据
    getPaymentList() {
      this.listLoading = true;
      getPayments(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.paymentList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },
    // 支付明细
    getPayDetailList() {
      this.listLoading_detail = true;
      getPaymentDetails(this.listCondition)
        .then((res) => {
          this.total_detail = res.count;
          this.payDetailList = res.results;
          this.listLoading_detail = false;
        })
        .catch((error) => {
          this.$message.error("获取数据失败");
          this.listLoading_detail = false;
        });
    },
    handleTabClick(tab, event) {
      if (tab.name === "detail") {
        this.getPayDetailList();
      }
    },
    getEmployeeList() {
      getEmployeeList().then((res) => {
        this.employees = res;
      });
    },
    getSales() {
      const query = {
        case: 1,
      };
      getSaleList(query)
        .then((res) => {
          this.sales = res;
        })
        .catch((error) => {
          this.$message.error("获取销售单数据失败");
        });
    },
    getAccounts() {
      get_account_titles({}).then((res) => {
        this.accountList = res;
      });
    },
    getBankList() {
      getBanks().then((res) => {
        this.banks = res;
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "payment_money") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else if (column.property === "money") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
          return;
        } else {
          return;
        }
      });
      return sums;
    },
    getDetailSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "money") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
          return;
        } else {
          return;
        }
      });
      return sums;
    },
    dataFormatter(row, column, cellValue, index) {
      if (
        column.property == "total_money" ||
        column.property == "payment_money" ||
        column.property == "money"
      ) {
        return cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getPaymentList();
    },
    // 详细查询
    handleDetailFilter() {
      this.listCondition.page = 1;
      this.getPayDetailList();
    },
    // 增加
    handleAdd() {
      this.paymentForm = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.paymentFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.paymentForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        // this.selectedKeys = getParentsPath(
        //   this.paymentForm.acc_title,
        //   this.accountList
        // );
        this.$refs.paymentFormRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delPayment(row.id);

          this.paymentList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async HandleSave() {
      this.$refs.paymentFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.paymentForm.user) {
            this.paymentForm.user = this.uid;
          }
          res = await updatePayment(this.paymentForm);
          const index = this.paymentList.findIndex((v) => v.id === res.id);
          this.paymentList.splice(index, 1, res);
        } else {
          this.paymentForm.user = this.uid;
          res = await addPayment(this.paymentForm);
          const { id } = res;
          if (id > 0) {
            this.getPaymentList();
            this.getSales();
          }
        }

        const { order_no, sale_order_name, payment_money } = res;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>支付单号: ${order_no}</div>
              <div>销售单号: ${sale_order_name}</div>
              <div>支付金额: ${payment_money}</div>
            `,
          type: "success",
        });
      });
    },
    handleChange(value) {
      if (this.selectedKeys.length > 0) {
        this.paymentForm.acc_title = this.selectedKeys[
          this.selectedKeys.length - 1
        ];
      } else {
        this.paymentForm.acc_title = undefined;
      }
    },
    selectChange(value) {
      if (!value) {
        this.paymentForm.details = [];
        return;
      }
      const sale = this.sales.find((v) => v.id == value);
      const total_money = sale.paid_money;
      this.paymentForm.customer_name = sale.customer_name;
      this.paymentForm.details = [];

      sale.lawyers.forEach((item, index) => {
        let temp = {
          id: undefined,
          payment: undefined,
          lawyer: item.employee,
          post: item.post,
          ratio: item.ratio,
          money: total_money * item.ratio * 0.01,
          desc: "",
        };
        this.paymentForm.details.push(temp);
        // this.inputMoney();
      });
    },
    // inputMoney() {
    //   let values = this.paymentForm.details.map((item) => +item.money);
    //   let sum = values.reduce((prev, curr) => {
    //     return prev + curr;
    //   });
    //   this.paymentForm.payment_money = sum;
    // },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }

  .item {
    margin-top: 8px;
  }
}
</style>